package com.bootdo.order.service.impl;

import static com.bootdo.common.utils.ShiroUtils.getUserId;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.bootdo.common.redis.lock.CommonRedisLock;
import com.bootdo.common.utils.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.config.Constant;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.mq.RabbitUtil;
import com.bootdo.order.dao.OrderDao;
import com.bootdo.order.dao.OrderPayDao;
import com.bootdo.order.dao.ReceiptDao;
import com.bootdo.order.domain.OrderDO;
import com.bootdo.order.domain.OrderPayDO;
import com.bootdo.order.domain.ReceiptDO;
import com.bootdo.order.service.ReceiptService;
import com.bootdo.system.dao.UserRoleDao;

@Service
public class ReceiptServiceImpl implements ReceiptService {

	private static Logger logger = LoggerFactory.getLogger(ReceiptServiceImpl.class);

	@Autowired
	private ReceiptDao receiptMapper;
	@Autowired
	private UserRoleDao userRoleMapper;
	@Autowired
	private OrderPayDao orderPayMapper;
	@Autowired
	private OrderDao orderMapper;
	@Autowired
	private RabbitUtil rabbitUtil;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public ReceiptDO get(Long id){
		return receiptMapper.get(id);
	}
	
	@Override
	public List<ReceiptDO> list(Map<String, Object> map){
		//格式话日期
		String startDate = (String) map.get("startTime");
		String endDate = (String) map.get("endTime");
		if (StringUtils.isNotBlank(startDate)){
			startDate = DateUtils.getDateOfFormat(startDate, "yyyy-MM-dd") + " 00:00:00";
			endDate = DateUtils.getDateOfFormat(endDate, "yyyy-MM-dd") + " 23:59:59";
			map.put("startTime", startDate);
			map.put("endTime", endDate);
		}
		//获取用户权限
		int checkUserIsManager = userRoleMapper.checkUserIsManager(getUserId());
		if (checkUserIsManager != 1){
			map.put("userId", getUserId());
		}
		return receiptMapper.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return receiptMapper.count(map);
	}

	/**
	 * 执行审核
	 * 		当审核通过时，恢复收款户额度
	 * @param receipt
	 * @return
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout=36000,rollbackFor=Exception.class)
	public int update(ReceiptDO receipt){
		CommonRedisLock commonLock = new CommonRedisLock(stringRedisTemplate, "EXAMINE_UPDATE_" + receipt.getId());
		try {
			if (commonLock.tryLock(3)) {
				int status = receipt.getStatus();
				if (receipt.getStatus() == 1){
					//审核通过恢复当前收款户额度
					receipt = receiptMapper.get(receipt.getId());
					if (0 != receipt.getStatus().intValue()) {
						return -2;
					}

					OrderPayDO orderPay = orderPayMapper.getByOrderId(receipt.getOrderId());
					JSONObject object = new JSONObject();
					object.put("date", DateUtils.format(new Date(),DateUtils.DATE_TIME_PATTERN));
					object.put("userId", receipt.getPayeeId());
					object.put("money", orderPay.getPayeeTurn());
					object.put("orderId", orderPay.getOrderId());
					object.put("reason", "回单新增");
					object.put("type", 1);
					rabbitUtil.sendToQueue(Constant.UPDATE_QUOTA, object.toJSONString());

					//修改订单状态为已完成
					orderPay.setStatus(5);
					orderPayMapper.update(orderPay);
					OrderDO order = new OrderDO();
					order.setId(orderPay.getOrderId());
					order.setType(5);
					orderMapper.update(order);
				}
				receipt.setLatestStatus(0);
				receipt.setStatus(status);
				return receiptMapper.update(receipt);
			}
		} catch (Exception e) {
			logger.error("回单异常" + ExceptionUtils.getExceptionAllinformation(e));
			return 0;
		} finally {
			commonLock.unlock();
		}
		return 0;
	}
	
}
